package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 处理物流信息（商品寄送的地址）
 */
@Slf4j
@Component
public class LogisticalHandler extends AbstractTransHandler {

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderConverter orderConverter;

    @Override
    public boolean isAsync() {
        return false;
    }

    /**
     * 向物流表中增加一条数据
     *
     * @param context 封存有请求相关信息的对象
     * @return boolean
     * @author Chen_Feng
     * @since 2022/07/09 13:50
     */
    @Override
    // @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 转化为OrderShipping
        OrderShipping orderShipping = orderConverter.context2Ordershipping(createOrderContext);

        // 将收货地址拆分成 省-市-区-街
        String address = createOrderContext.getStreetName();
        String[] split = address.split("-");
        if (split.length != 4) {
            throw new ValidateException(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode(), "地址信息异常");
        }
        String receiverState = split[0];
        String receiverCity = split[1];
        String receiverDistrict = split[2];
        String receiverAddress = split[3];

        // 补充OrderShipping信息
        orderShipping.setReceiverState(receiverState);
        orderShipping.setReceiverCity(receiverCity);
        orderShipping.setReceiverDistrict(receiverDistrict);
        orderShipping.setReceiverAddress(receiverAddress);

        // 向数据库order-shipping表插入数据
        try {
            orderShippingMapper.insertSelective(orderShipping);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ValidateException(OrderRetCode.SHIPPING_DB_SAVED_FAILED.getCode(), OrderRetCode.SHIPPING_DB_SAVED_FAILED.getMessage());
        }

        return true;
    }
}
